package com.easy.mongodb.starter.config;

import cn.hutool.core.util.StrUtil;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.connection.ConnectionPoolSettings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ProjectName: easy-mongodb
 * Description: mongodb自动配置
 *
 * @Author: vapeshop
 * Date: 2022/6/15 20:39:18
 * UpdateUser: vapeshop
 * UpdateDate: 2022/6/15 20:39:18
 * UpdateRemark: The modified content
 * Version: 1.0
 * <p>
 * Copyright © 2022 vapeshop Technologies Inc. All Rights Reserved
 **/
@Configuration
@ConditionalOnClass(MongoClient.class)
@EnableConfigurationProperties(EasyMongoDBConfigProperties.class)
@ConditionalOnProperty(prefix = "easy-mongodb", name = {"enable"}, havingValue = "true", matchIfMissing = true)
public class MongoConfig {
    @Autowired
    private EasyMongoDBConfigProperties easyMongoDBConfigProperties;

    /**
     * mongoClient
     *
     * @return mongoClient bean
     */
    @Bean
    @ConditionalOnMissingBean
    public MongoClient mongoClient() {
        // 处理地址
//        String address = easyMongoDBConfigProperties.getAddress();
//        if (StringUtils.isEmpty(address)) {
//            throw ExceptionUtils.build("please config the mongodb address");
//        }
//        com.mongodb.internal.connection.InternalConnectionPoolSettings
//        System.out.println("easyMongoDBConfigProperties=" + easyMongoDBConfigProperties);
        List<ServerAddress> serverAddressList = new ArrayList<>();

        for (String s : this.easyMongoDBConfigProperties.getAddress()) {
            String host = s.substring(0, s.lastIndexOf(":"));
            String port = s.substring(s.lastIndexOf(":") + 1);
            serverAddressList.add(new ServerAddress(host, Integer.parseInt(port)));
        }

        // 连接认证，如果设置了用户名和密码的话
        MongoClientSettings settings = null;
        ConnectionPoolSettings poolSetting = ConnectionPoolSettings.builder().
                maxWaitTime(this.easyMongoDBConfigProperties.getMaxWaitTime(), TimeUnit.MILLISECONDS).build();
        if (StrUtil.isNotBlank(this.easyMongoDBConfigProperties.getUsername())) {
            MongoCredential credential = MongoCredential.createScramSha1Credential(this.easyMongoDBConfigProperties.getUsername(),
                    this.easyMongoDBConfigProperties.getAuthDB(), this.easyMongoDBConfigProperties.getPassword().toCharArray());
            settings = MongoClientSettings.builder()
                    .credential(credential)
                    .applyToConnectionPoolSettings(builder -> builder.applySettings(poolSetting))
                    .applyToClusterSettings(builder -> builder.hosts(serverAddressList)).build();
        } else {
            settings = MongoClientSettings.builder().applyToConnectionPoolSettings(builder -> builder.applySettings(poolSetting))
                    .applyToClusterSettings(builder -> builder.hosts(serverAddressList)).build();
        }
//
//        MongoClient mongoClient = MongoClients.create(settings);
//        ConnectionString connString = new ConnectionString(
//                "mongodb+srv://<username>:<password>@<cluster-address>/test?w=majority"
//        );
//        ConnectionString connString = new ConnectionString(address);
//        MongoClientSettings settings = MongoClientSettings.builder()
//                .applyConnectionString(connString)
//                .retryWrites(true)
//                .build();
        MongoClient mongoClient = MongoClients.create(settings);
//        MongoClient mongoClient = MongoClients.create(
//                MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb://doudou-admin:'admin.1qazXSW.password'@angledoudou.top:27017,angledoudou.top:27018,angledoudou.top:27019/rouyi-vue?w=majority"))
//                        .applyToServerSettings(builder ->
//                                builder.minHeartbeatFrequency(700, MILLISECONDS)
//                                        .heartbeatFrequency(15, SECONDS))
//                        .build());
        return mongoClient;

    }

}
